package common.util;

import java.lang.reflect.Field;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import javax.faces.FacesException;
import javax.faces.context.FacesContext;

/**
 *
 * @author shousuke
 */
public class CommonUtil {

    private static final String BUNDLE_NAME = "common.messages";

    public static Map<String, String> getConstantsAsMap(String className) {
        Map<String, String> result = new HashMap<String, String>();
        try {
            Class<?> c = Class.forName(className);
            Field[] fields = c.getDeclaredFields();
            for (Field field : fields) {
                result.put(field.getName(), (String) field.get(null));
            }
            return result;
        } catch (ClassNotFoundException e) {
            throw new FacesException(e);
        } catch (IllegalAccessException e) {
            throw new FacesException(e);
        }
    }

    public static List<String> getConstantsAsList(String className) {
        List<String> result = new ArrayList<String>();
        try {
            Class<?> c = Class.forName(className);
            Field[] fields = c.getDeclaredFields();
            for (Field field : fields) {
                result.add((String) field.get(null));
            }
            return result;
        } catch (ClassNotFoundException e) {
            throw new FacesException(e);
        } catch (IllegalAccessException e) {
            throw new FacesException(e);
        }
    }

    public static String getMessageResource(String key, Object[] arguments) {
        FacesContext context = FacesContext.getCurrentInstance();
        String resourceString;
        try {
            ResourceBundle bundle = ResourceBundle.getBundle(BUNDLE_NAME, context.getViewRoot().getLocale());
            resourceString = bundle.getString(key);
        } catch (MissingResourceException e) {
            return key;
        }

        if (arguments == null) {
            return resourceString;
        }
        MessageFormat format = new MessageFormat(resourceString, context.getViewRoot().getLocale());
        return format.format(arguments);
    }
}
